package guet.dream.question.servlet;

import guet.dream.question.Question;
import guet.dream.question.QuestionDaoImpl;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class QEditServlet
 */
public class QEditServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		QuestionDaoImpl questionDao = new QuestionDaoImpl();
		Question question = questionDao.findById(Integer.valueOf(id));
		request.setAttribute("question", question);
		
        RequestDispatcher view = request.getRequestDispatcher("/question/edit.jsp");
        view.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String successViewName="/question/success.jsp";
		String errorViewName = "/question/error.jsp";
		
		String id = request.getParameter("id");
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		
		QuestionDaoImpl questionDao = new QuestionDaoImpl();
		Question question = new Question(Integer.valueOf(id),title,content);
		int count = questionDao.update(question);
		request.setAttribute("flag", count);
		request.setAttribute("id", Integer.valueOf(id));//查看修改结果链接用到.
		
		
		String viewName= (count==1?successViewName:errorViewName);
		
		RequestDispatcher view = request.getRequestDispatcher(viewName);
		view.forward(request, response);
	}

}
